package gui;

import classes.CargoEfetivo;
import java.awt.event.KeyEvent;
import org.apache.commons.lang3.StringUtils;
import erro.ConexaoException;
import erro.ConsultaException;
import fachada.Fachada;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class CargoEfetivoCadastrar extends javax.swing.JFrame {

    public CargoEfetivoCadastrar() {
        initComponents();
        setLocationRelativeTo(null);
        carregarTabela();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btSalvar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        textNomeCe = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbCargos = new javax.swing.JTable();
        btExcluir = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Cargo Efetivo");

        btSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/salvar.png"))); // NOI18N
        btSalvar.setText("Salvar");
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });
        btSalvar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btSalvarKeyPressed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Cargo Efetivo:");

        textNomeCe.setNextFocusableComponent(btSalvar);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(textNomeCe, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(18, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(textNomeCe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Cargos Efetivos:"));

        tbCargos.setAutoCreateRowSorter(true);
        tbCargos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null},
                {null},
                {null},
                {null}
            },
            new String [] {
                "Nome"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbCargos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbCargosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbCargos);

        btExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/excluir.png"))); // NOI18N
        btExcluir.setText("Excluir");
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });

        btAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/editar.png"))); // NOI18N
        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btExcluir, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
                    .addComponent(btAlterar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(btExcluir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btAlterar))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btSalvar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btSalvar)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
        try {
            Fachada f = new Fachada();
            CargoEfetivo ce = new CargoEfetivo();
            String cargo = textNomeCe.getText().toLowerCase().trim();
            StringTokenizer stPara = new StringTokenizer(cargo, " ");
            String convertido = "";
            while (stPara.hasMoreTokens()) {
                String fMaiuscula = StringUtils.capitalize(stPara.nextToken().trim() + " ");
                convertido += fMaiuscula;
            }
            ce.setNome(convertido);
            f.inserir(ce);
            textNomeCe.setText("");
            carregarTabela();
        } catch (ConexaoException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + e);
        } catch (ConsultaException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível inserir o novo cargo!\n" + e);
        }
    }//GEN-LAST:event_btSalvarActionPerformed

    private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
        int selectedOption = JOptionPane.showConfirmDialog(null, "Deseja realmente excluir?", "Alerta!", JOptionPane.YES_NO_OPTION);
        if (selectedOption == JOptionPane.YES_OPTION) {
            int size = tbCargos.getSelectedRowCount();
            if (size > 1) {
                JOptionPane.showMessageDialog(null, "Selecione apenas um cargo por vez!");
                tbCargos.setSelectionMode(1);
            } else {
                CargoEfetivo e = new CargoEfetivo();
                Fachada f = new Fachada();
                ArrayList<CargoEfetivo> lista;
                try {
                    lista = f.listar(e);
                    DefaultTableModel modelo = (DefaultTableModel) tbCargos.getModel();
                    int r = tbCargos.getSelectedRow();
                    String servAtual = modelo.getValueAt(r, 0).toString();
                    for (CargoEfetivo ce : lista) {
                        if (ce.getNome().equals(servAtual)) {
                            f.deletar(ce);
                            carregarTabela();
                        }
                    }
                } catch (ConexaoException ex) {
                    JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
                } catch (ConsultaException ex) {
                    JOptionPane.showMessageDialog(null, "Cargo em uso!");
                }
            }
        } else {
            this.repaint();
        }
    }//GEN-LAST:event_btExcluirActionPerformed

    private void btSalvarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btSalvarKeyPressed
        if (KeyEvent.getKeyText(evt.getKeyCode()).equals("Enter")) {
            btSalvarActionPerformed(null);
        }
    }//GEN-LAST:event_btSalvarKeyPressed

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        CargoEfetivo c = new CargoEfetivo();
        Fachada f = new Fachada();
        ArrayList<CargoEfetivo> lista;
        try {
            lista = f.listar(c);
            DefaultTableModel modelo = (DefaultTableModel) tbCargos.getModel();
            int r = tbCargos.getSelectedRow();
            String atual = modelo.getValueAt(r, 0).toString();
            for (CargoEfetivo ce : lista) {
                if (ce.getNome().equals(atual)) {
                    String cargo = textNomeCe.getText().toLowerCase().trim();
                    StringTokenizer stPara = new StringTokenizer(cargo, " ");
                    String convertido = "";
                    while (stPara.hasMoreTokens()) {
                        String fMaiuscula = StringUtils.capitalize(stPara.nextToken().trim() + " ");
                        convertido += fMaiuscula;
                    }
                    ce.setNome(convertido);                    
                    ce.setCargoE_id(ce.getCargoE_id());
                    f.alterarCe(ce);
                    carregarTabela();
                    textNomeCe.setText("");
                }
            }
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível alterar o Cargo.\n " + ex);
        }
    }//GEN-LAST:event_btAlterarActionPerformed

    private void tbCargosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbCargosMouseClicked
        if (evt.getClickCount() == 2 || evt.getButton() == MouseEvent.BUTTON1) {//se o clique for duplo
            DefaultTableModel modelo = (DefaultTableModel) tbCargos.getModel();
            int r = tbCargos.getSelectedRow();
            String atual = modelo.getValueAt(r, 0).toString();
            textNomeCe.setText(atual);
        }
    }//GEN-LAST:event_tbCargosMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CargoEfetivoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CargoEfetivoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CargoEfetivoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CargoEfetivoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new CargoEfetivoCadastrar().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btSalvar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbCargos;
    private javax.swing.JTextField textNomeCe;
    // End of variables declaration//GEN-END:variables

    public final void carregarTabela() {
        Fachada f = new Fachada();
        CargoEfetivo cs = new CargoEfetivo();
        DefaultTableModel modelo = (DefaultTableModel) tbCargos.getModel();
        modelo.setNumRows(0);
        ArrayList<CargoEfetivo> lista = new ArrayList<CargoEfetivo>();
        try {
            lista = f.listar(cs);
            for (int i = 0; i < lista.size(); i++) {
                if (lista.get(i).getCargoE_id() != 1) {
                    modelo.addRow(new Object[]{lista.get(i).getNome()});
                }
            }
            tbCargos.setModel(modelo);
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar carregar a tabela.\n" + ex);
        }
    }
}
